package com.itheima.controller;

import com.itheima.dto.FileInfo;
import org.apache.commons.io.FileUtils;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
//    @Value("${ydd.path}")
//    private String path;

    @PostMapping("upload")
    public R<Object> upload(String type, MultipartFile file) {
        String dirPath = System.getProperty("user.dir") + "\\nginx-1.8.0-backend\\html\\dist\\undefinedupload\\images\\20211101\\";
        String dirPath2 = System.getProperty("user.dir") + "\\nginx-front\\html\\dist\\apiupload\\images\\20211101\\";
        log.info(dirPath);
        try {
            String fileName = Long.toString(System.currentTimeMillis());
            String endName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String targetName = fileName + endName;
            File targetDir = new File(dirPath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File targetFile = new File(dirPath, targetName);
            if (targetFile.exists()){
                targetFile.delete();//如果文件存在,则删除
            }
            file.transferTo(targetFile);

            File file2 = new File(dirPath2,targetName);
            FileUtils.copyFile(targetFile,file2);


            FileInfo fileInfo = new FileInfo();
            fileInfo.setSavePath("upload/images/20211101/" + targetName);
            fileInfo.setName(file.getOriginalFilename());
            fileInfo.setMime("image/" + endName.replaceAll("\\.", ""));
            fileInfo.setSize((int) targetFile.length());
            return R.success(fileInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败：" + e.getMessage());
        }
    }
}